import 'dart:typed_data';
import 'package:ble_ota_plugin/library.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

/// 一个简单的演示：展示如何使用 `OtaUpgradeManager` 启动下载、传输、暂停/恢复与取消。
class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late OtaUpgradeManager _manager;
  String _firmwareUrl = 'https://speed.hetzner.de/100KB.bin';
  String _statusText = 'idle';
  double _progress = 0.0;
  int _totalSize = 0;

  @override
  void initState() {
    super.initState();
    _createManager();
  }

  void _createManager() {
    _manager = OtaUpgradeManager(
      firmwareUrl: _firmwareUrl,
      // 一个示例的 sendData 实现：模拟每个数据包发送需要一些时间并返回成功
      sendData: (Uint8List bytes) async {
        await Future.delayed(const Duration(milliseconds: 50));
        return true;
      },
      onProgress: (double progress, int position) {
        setState(() {
          _progress = progress;
        });
      },
      onStatus: (OtaUpgradeStatus status) {
        setState(() {
          _statusText = status.toString().split('.').last;
        });
      },
      onUserActionRequired: (UserActionType action) {
        // 在真实场景中应该提示用户，例如重启设备或确认升级
        // 这里仅在控制台打印并在 UI 中显示
        setState(() {
          _statusText =
              'waiting for user: ${action.toString().split('.').last}';
        });
      },
      onTotalSize: (int totalSize) {
        setState(() {
          _totalSize = totalSize;
        });
      },
      // 缩短示例中升级等待时间
      upgradeSimulationSteps: 5,
      upgradeStepDuration: const Duration(milliseconds: 100),
    );
  }

  @override
  void dispose() {
    _manager.dispose();
    super.dispose();
  }

  Future<void> _startUpgrade() async {
    setState(() {
      _statusText = 'starting';
      _progress = 0.0;
    });

    try {
      await _manager.startUpgrade();
    } catch (e) {
      setState(() {
        _statusText = 'error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('OTA Upgrade Demo'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('Firmware URL:'),
              TextFormField(
                initialValue: _firmwareUrl,
                onChanged: (v) => _firmwareUrl = v,
                decoration: const InputDecoration(border: OutlineInputBorder()),
              ),
              const SizedBox(height: 12),
              Row(
                children: [
                  ElevatedButton(
                    onPressed: () {
                      // 重新创建 manager（如果 URL 变更时）
                      _manager.dispose();
                      _createManager();
                      _startUpgrade();
                    },
                    child: const Text('Start Upgrade'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () => _manager.pauseTransfer(),
                    child: const Text('Pause'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () => _manager.resumeTransfer(),
                    child: const Text('Resume'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () => _manager.cancelUpgrade(),
                    child: const Text('Cancel'),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              Text('Status: $_statusText'),
              const SizedBox(height: 8),
              LinearProgressIndicator(value: _progress),
              const SizedBox(height: 8),
              Text(
                  'Progress: ${(100 * _progress).toStringAsFixed(1)}% ($_totalSize bytes)'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () async {
                  // 演示：在等待用户动作时调用 onUserActionCompleted
                  await _manager
                      .onUserActionCompleted(UserActionType.restartDevice);
                },
                child: const Text('Simulate User Restart'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
